package com.lineng.service.impl;

import java.util.Date;
import java.util.List;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.lineng.dao.StudentMapper;
import com.lineng.pojo.Student;
import com.lineng.service.StudentService;
import com.lineng.util.FileUtils;
import com.lineng.util.VerificationUtil;

@Service
public class StudentServiceImpl implements StudentService {

	@Autowired
	StudentMapper studentMapper;

	@Autowired
	private HttpServletRequest request;

	public List<Student> getStudent() {

		List<Student> students = studentMapper.selectByExampleWithBLOBs(null);
		if (VerificationUtil.verification(request) == 0) {
			for (int i = 0; i < students.size(); i++) {

				if (students.get(i).getReader() != null && students.get(i).getReader() != 0) {
					int result = students.get(i).getReader() + 1;
					studentMapper.updateStudentReader(result);
				} else {
					studentMapper.updateStudentReader(1);
				}
			}
		}
		return students;
	}

	public int updateStudent(Student student, MultipartFile file, String username) {
		int num = 0;
		if (VerificationUtil.verification(request) == 1) {
			// 获得项目的路径
			ServletContext sc = request.getSession().getServletContext();
			// 上传位置
			String path = sc.getRealPath("/") + student.getPath(); // 设定文件保存的目录
			if (file != null) {
				try {
					FileUtils.saveFile(file, path, 997, 729);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			if (student != null) {
				student.setPeople(username);
				student.setDate(new Date());
				num = studentMapper.updateByPrimaryKeySelective(student);
			}
			return num;
		}
		return num;
	}

}
